package jddk;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.config.MessageConstraints;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.io.DefaultHttpRequestParserFactory;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.io.SessionInputBufferImpl;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.message.BasicHeader;

import com.google.common.base.Charsets;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.io.NioUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.socket.nio.ChannelHandler;
import cn.hutool.socket.nio.NioServer;
import lombok.extern.slf4j.Slf4j;

public class SocketTest {

	private static final Log logger = LogFactory.get();

	public static void main(String[] args) throws IOException {

		//6217002870011081260
		//6236682870005834754
		//62170028700816150015
		//6217002870081615005

		String req = String.format("%-28s", "6236682870005834754");
		byte[] result = new SocketClient("128.1.108.215", 20100).send(req.getBytes());
		System.out.println(new String(result) + "!");
		
		
		String resCode = StringUtils.trimToEmpty(new String(result, 0, 12));
		String resMsg = StringUtils.trimToEmpty(new String(result, 12, 60, Charsets.UTF_8));
		String resCardNo = StringUtils.trimToEmpty(new String(result, 72, 28));
		String balance = StringUtils.trimToEmpty(new String(result, 100, 16));
		String cardType = StringUtils.trimToEmpty(new String(result, 116, 4));
		String cardNo = StringUtils.trimToEmpty(new String(result, 120, 28));
		String stName = StringUtils.trimToEmpty(new String(result, 148, 40, Charsets.UTF_8));
		
		
		//test2();

		//String abc = "YDCA03410001此客户不存在#106001#FBASCST1##                                                                    ";

		////int a = StringUtils.indexOf(abc, "|");
		//System.out.println(StringUtils.substring(abc, 12, StringUtils.indexOf(abc, "|")));

		// 1.00000000000 成功  
		//test2();

		/*byte[] request001Byte = FileUtils.readFileToByteArray(new File("D:/xmlwydz/request001.txt"));
		byte[] request001BytewithLength = buildAddHeaderLengthResult(request001Byte);
		
		System.out.println(new String(request001BytewithLength));
		
		byte[] result = new SocketClient("128.1.108.236", 9922).send(request001BytewithLength);
		System.out.println(new String(result));*/

		//HttpUtils.get("http://128.1.108.238:8101/ccbhousing/login");

	}

	protected static byte[] buildAddHeaderLengthResult(byte[] result) {
		try {
			int contentLength = result.length;
			String lengthStr = StringUtils.leftPad(contentLength + "", 8, "0");
			byte[] allContent = ArrayUtils.addAll(lengthStr.getBytes("GBK"), result);
			return allContent;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void test3() throws Exception {
		NioServer server = new NioServer(9999);

		server.setChannelHandler(new ChannelHandler() {
			@Override
			public void handle(SocketChannel socketChannel) throws Exception {
				FastByteArrayOutputStream outStream = NioUtil.read(socketChannel);
				System.out.println("=================================================");
				String content = new String(outStream.toByteArray());
				System.out.println(content);

				//socketChannel.write(ByteBuffer.wrap(outStream.toByteArray()));

				SessionInputBufferImpl session = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 1024);
				session.bind(new ByteArrayInputStream(outStream.toByteArray()));
				HttpMessageParser<HttpRequest> parser = DefaultHttpRequestParserFactory.INSTANCE.create(session, MessageConstraints.DEFAULT);
				HttpRequest request = parser.parse();
				System.out.println("before: " + request.getFirstHeader("Host"));
				request.setHeader(new BasicHeader("Host", "128.1.108.238:8101"));
				System.out.println("after: " + request.getFirstHeader("Host"));
				System.out.println("==request: " + request);
				System.out.println("==================Response====================");

				CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpHost("128.1.108.238", 8101), request);
				System.out.println("getProtocolVersion: " + response.getProtocolVersion());
				System.out.println("getStatusLine: " + response.getStatusLine());

				//System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));

				//将报文进行修正发到第三方
				socketChannel.write(ByteBuffer.wrap("a".getBytes()));
				socketChannel.close();
				//socketChannel 一定要关闭, 不然select 会一直返回这个通道,进入死循环
			}
		});

		server.start();

		server.close();
	}

	private static void test2() {
		try {
			Socket socket = new Socket("128.1.108.215", 20100);
			PrintWriter os = new PrintWriter(socket.getOutputStream());
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			String req = String.format("%-28s", "6236682870005834754");
			System.out.println(req + "!");

			os.print(req + "\n");
			os.flush();
			System.out.println("Server:" + is.readLine() + "==");

			// 继续循环
			os.close(); // 关闭Socket输出流
			is.close(); // 关闭Socket输入流
			socket.close(); // 关闭Socket
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void test1() {
		try {
			Socket socket = new Socket("128.1.108.215", 20100);
			PrintWriter os = new PrintWriter(socket.getOutputStream());
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			String bwcd = "00000240";
			String jydm = "200000";
			String fwdm = "0200";
			String zdbsm = "420147237004";
			String dwbm = "420147237000017     ";
			String dsfrq = "20210315";
			String dsfsj = "141501";
			String dsflsh = "20210315141501000000000000000001";
			String mac = "162930          ";
			String gnh = "1";
			String blzd = "                                                                                                                               ";
			String req = bwcd + jydm + fwdm + zdbsm + dwbm + dsfrq + dsfsj + dsflsh + mac + gnh + blzd;
			os.print(req + "");
			os.flush();
			System.out.println("Server:" + is.readLine());

			// 继续循环
			os.close(); // 关闭Socket输出流
			is.close(); // 关闭Socket输入流
			socket.close(); // 关闭Socket
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
